package com.wzx.user.service.impl;

import com.wzx.admin.pojo.RedPkgControl;
import com.wzx.common.constants.CoreConstants;
import com.wzx.user.dto.RedPkgDto;
import com.wzx.user.service.RedisControlService;
import com.wzx.user.utils.AmountUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.bcel.Const;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author wzx
 * @version 1.0
 * @date 2023/11/13 - 10:35
 * @description 标题
 */
@Slf4j
@Service
public class RedisControlServiceImpl implements RedisControlService {

    @Autowired
    private RedisTemplate redisTemplate;

    private static final String defaultTitle = "大吉大利";

    /**
     * 1，新增，抢包闪避
     *
     * @param groupId
     * @param userId
     */
    @Override
    public void addControlNum(Integer groupId, Integer userId) {
        String redisKey = CoreConstants.CoreControl.CONTROL_ROB_PREFIX + groupId + "-" + userId;
        RedPkgControl redPkgControl = (RedPkgControl) redisTemplate.opsForValue().get(redisKey);

        if (redPkgControl != null) {
            if (redPkgControl.getRobNum() != null) {
                redPkgControl.setRobNum(redPkgControl.getRobNum() + 1);
                if (redPkgControl.getRobNum() > 10) {
                    redPkgControl.setRobNum(0);
                }
            } else {
                redPkgControl.setRobNum(1);
            }
            redisTemplate.opsForValue().set(redisKey, redPkgControl);
        }

    }

    /**
     * 2，抢包，避开有雷值的金额
     *
     * @param redPkgDto
     * @param userId
     * @param generateArr
     * @param generateIndex
     * @return
     */
    @Override
    public RedPkgDto getRedPkgPrice(RedPkgDto redPkgDto, Integer userId, int[] generateArr, Integer generateIndex) {
        //1，获取redis中存储的数据
        String redisKey = CoreConstants.CoreControl.CONTROL_ROB_PREFIX + redPkgDto.getGroupId() + "-" + userId;
        log.info("用户：{}，在群聊：{}，中抢包", userId, redPkgDto.getGroupId());
        RedPkgControl redPkgControl = (RedPkgControl) redisTemplate.opsForValue().get(redisKey);
        if (redPkgControl == null) {
            //2，没有设置过，直接返回即可
            redPkgDto.setRobAmountByInt(generateArr[generateIndex]);
            log.info("用户：{}，没有设置过躲避，跳过即可", userId);
            return redPkgDto;
        }

        //2.1，判断 倍率
        String magnification = redPkgControl.getPercentage();
        int percentageNum = Integer.parseInt(magnification) / 10;

        if (redPkgControl.getRobNum() != null && percentageNum < redPkgControl.getRobNum()) {
            redPkgDto.setRobAmountByInt(generateArr[generateIndex]);
            log.info("用户：{}，躲避倍率已达上线，跳过即可", userId);
            return redPkgDto;
        }
        //3，根据判断，是那种类型
        switch (redPkgControl.getGameplayType()) {
            case "1":
                //3.1，雷值玩法
                if (redPkgDto.getTitle().equals(defaultTitle)) {
                    log.info("用户{}，使用默认雷值为1开始处理...", userId);
                    //3.1.1默认玩法，雷值为1
                    int robAmount = generateArr[generateIndex];
                    int lastAmount = robAmount % 10;
                    if (lastAmount == 1) {
                        //1，中雷了
                        log.info("用户{}，使用默认雷值为1，中雷了", userId);
                        //获取剩下的 几个金额
                        for (int i = generateIndex + 1; i < generateArr.length; i++) {
                            int exchangeAmountLast = generateArr[i] % 10;
                            if (exchangeAmountLast != 1) {

                                int temp = generateArr[i];
                                generateArr[i] = robAmount;
                                generateArr[generateIndex] = temp;
                                log.info("用户{}躲避雷值成功！，和将自己金额：{}和另一个金额：{}交换成功！", userId, robAmount, temp);

                                //交换手气最佳下标
                                if (Objects.equals(redPkgDto.getMaxIndex(), generateIndex)) {
                                    redPkgDto.setMaxIndex(i);
                                } else if (redPkgDto.getMaxIndex() == i) {
                                    redPkgDto.setMaxIndex(generateIndex);
                                }

                                break;
                            }
                        }
                    }
                    redPkgDto.setRobAmountByInt(generateArr[generateIndex]);
                } else {
                    double totalAmount = redPkgDto.getTotalAmount();
                    String totalAmountStr = totalAmount + "";
                    boolean isMatched = redPkgDto.getTitle().startsWith(totalAmountStr);
                    if (isMatched) {
                        //3.1.2，标题带雷值
                        log.info("用户{}，使用标题带雷值开始处理...", userId);
                        String mine = redPkgDto.getTitle().substring(totalAmountStr.length(), redPkgDto.getTitle().length());
                        String[] mineArr = extractNumbers(mine);
                        //获取最后一个字符
                        int robAmount = generateArr[generateIndex];
                        int lastAmount = robAmount % 10;

                        for (String mineOne : mineArr) {
                            if (mineOne.equals(lastAmount + "")) {
                                //中雷了
                                log.info("用户{}，使用标题带雷值中雷了.", userId);
                                for (int i = generateIndex + 1; i < generateArr.length; i++) {
                                    int exchangeAmountLast = generateArr[i] % 10;

                                    boolean isEquation = queryIsEquation(mineArr, exchangeAmountLast + "");
                                    if (isEquation) {
                                        int temp = generateArr[i];
                                        generateArr[i] = robAmount;
                                        generateArr[generateIndex] = temp;

                                        //交换手气最佳的下标
                                        if (Objects.equals(redPkgDto.getMaxIndex(), generateIndex)) {
                                            redPkgDto.setMaxIndex(i);
                                        } else if (redPkgDto.getMaxIndex() == i) {
                                            redPkgDto.setMaxIndex(generateIndex);
                                        }
                                        break;
                                    }
                                }
                            }
                        }

                    } else {
                        //3.1.3，标题全为雷
                        log.info("用户{}，使用标题全为雷开始处理...", userId);
                        String[] mineArr = extractNumbers(redPkgDto.getTitle());
                        int robAmount = generateArr[generateIndex];
                        int lastAmount = robAmount % 10;

                        for (String mineOne : mineArr) {
                            if (mineOne.equals(lastAmount + "")) {
                                //中雷了
                                log.info("用户{}，使用标题全为雷中雷了", userId);
                                for (int i = generateIndex + 1; i < generateArr.length; i++) {
                                    int exchangeAmountLast = generateArr[i] % 10;

                                    boolean isEquation = queryIsEquation(mineArr, exchangeAmountLast + "");
                                    if (isEquation) {
                                        int temp = generateArr[i];
                                        generateArr[i] = robAmount;
                                        generateArr[generateIndex] = temp;

                                        //交换手气最佳的下标
                                        if (Objects.equals(redPkgDto.getMaxIndex(), generateIndex)) {
                                            redPkgDto.setMaxIndex(i);
                                        } else if (redPkgDto.getMaxIndex() == i) {
                                            redPkgDto.setMaxIndex(generateIndex);
                                        }
                                        break;
                                    }
                                }
                            }
                        }

                    }
                    redPkgDto.setRobAmountByInt(generateArr[generateIndex]);
                }

                break;
            case "2":
                log.info("开始处理避开最大...");
                //3.2，避开最大
                int robAmount = generateArr[generateIndex];
                int robAmountNext = generateArr[generateIndex + 1];
                if (robAmount > robAmountNext) {
                    generateArr[generateIndex] = robAmountNext;
                    generateArr[generateIndex + 1] = robAmount;

                    //如果是手气最佳交换需要交换下标值
                    if (Objects.equals(redPkgDto.getMaxIndex(), generateIndex)) {
                        redPkgDto.setMaxIndex(generateIndex + 1);
                    } else if (redPkgDto.getMaxIndex() == generateIndex + 1) {
                        redPkgDto.setMaxIndex(generateIndex);
                    }
                }
                redPkgDto.setRobAmountByInt(generateArr[generateIndex]);
                log.info("避开最大调换成功！");
                break;
            case "3":
                //3.3，避开最小
                log.info("开始处理避开最小...");
                int robAmountMin = generateArr[generateIndex];
                int robAmountMinNext = generateArr[generateIndex + 1];
                if (robAmountMin < robAmountMinNext) {
                    generateArr[generateIndex] = robAmountMinNext;
                    generateArr[generateIndex + 1] = robAmountMin;

                    if (Objects.equals(redPkgDto.getMaxIndex(), generateIndex)) {
                        redPkgDto.setMaxIndex(generateIndex + 1);
                    } else if (redPkgDto.getMaxIndex() == generateIndex + 1) {
                        redPkgDto.setMaxIndex(generateIndex);
                    }
                }
                redPkgDto.setRobAmountByInt(generateArr[generateIndex]);
                log.info("避开最小调换成功！");
                break;
            default:
                break;
        }

        return redPkgDto;
    }

    @Override
    public int[] changeArray(Integer amount, int[] array, String title, Integer groupId, Integer userId) {
        //1，获取redis中存储的数据
        String redisKey = CoreConstants.CoreControl.CONTROL_SEND_PREFIX + groupId + "-" + userId;
        log.info("用户：{}，在群聊：{}，中抢包", userId, groupId);
        RedPkgControl redPkgControl = (RedPkgControl) redisTemplate.opsForValue().get(redisKey);
        if (redPkgControl == null) {
            //2，没有设置过，直接返回即可
            log.info("用户：{}，没有设置过躲避，跳过即可", userId);
            return changePosition(array);
        }

        //3，判断是否已经达到处理次数
        String magnification = redPkgControl.getPercentage();
        int percentageNum = Integer.parseInt(magnification) / 10;

        if (redPkgControl.getRobNum() != null && percentageNum < redPkgControl.getRobNum()) {
            log.info("用户：{}，已经达到处理次数", userId);
            return changePosition(array);
        }

        //4，设置过，根据标题判断
        if (title.equals(defaultTitle)) {
            log.info("用户{}，使用默认雷值为1开始处理...", userId);
            //4.1，判断 数组中每一个数字的尾数，是否含有雷值
            for (int i = 0; i < array.length; i++) {
                if (array[i] % 10 == 1) {
                    //含有，不用处理
                    log.info("用户：{}，含有雷值，不用处理", userId);
                    return changePosition(array);
                }
            }


        } else {
            double totalAmount = AmountUtils.handlerAmountByInteger(amount);
            String totalAmountStr = totalAmount + "";
            boolean isMatched = title.startsWith(totalAmountStr);
            if (isMatched) {
                //3.1.2，标题带雷值
                log.info("用户{}，使用标题带雷值开始处理...", userId);

            } else {
                //3.1.3，标题全为雷


            }

        }

        return new int[0];
    }

    public static int[] changePosition(int[] array) {
        //打乱顺序
        Integer[] newNums = Arrays.stream(array).boxed().toArray(Integer[]::new);
        List<Integer> list = Arrays.asList(newNums);
        Collections.shuffle(list);
        return list.stream().mapToInt(Integer::intValue).toArray();
    }


    public static String[] extractNumbers(String input) {
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(input);
        int count = 0;

        while (matcher.find()) {
            count++;
        }

        String[] numbers = new String[count];
        matcher.reset();

        for (int i = 0; i < count; i++) {
            if (matcher.find()) {
                numbers[i] = matcher.group();
            }
        }

        return numbers;
    }

    public static boolean queryIsEquation(String[] strArr, String lastNum) {
        for (int i = 0; i < strArr.length; i++) {
            if (lastNum.equals(strArr[i])) {
                return false;
            }
        }
        return true;
    }


}